﻿

using System.Net.Http.Headers;
using AlibabaCloud.SDK.Ocr_api20210707;
using AlibabaCloud.SDK.Ocr_api20210707.Models;
using Klear.Library.Helpers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Tea;

namespace Klear.Library.Services;
using AlibabaCloud.OpenApiClient.Models;


public class OcrService : IOcrService
{
    public Client CreateClient()
    {
        Config config = new Config
        {
            AccessKeyId = AccessKeyStorage.OCR_ID,
            AccessKeySecret = AccessKeyStorage.OCR_SECRET
        };
        config.Endpoint = AccessKeyStorage.OCR_ENDPOINT;
        Client client = new Client(config);
        return client;
    }
    public async Task<string> GetText(string imgPath)
    {
        if (!File.Exists(imgPath))
        {
            Console.WriteLine("File does not exist.");
            return null;
        }
        var client = CreateClient();
        if (client == null)
        {
            Console.WriteLine("Client initialization failed.");
            return null;
        }
        
        Console.WriteLine("正在进行OCR处理...");
        try
        {
            using (FileStream fileStream = new FileStream(imgPath, FileMode.Open, FileAccess.Read))
            {
                RecognizeBasicRequest request = new RecognizeBasicRequest
                {
                    Body = fileStream
                };
                if (request.Body == null)
                {
                    Console.WriteLine("Request body is null.");
                    return null;
                }
                RecognizeBasicResponse response = await client.RecognizeBasicAsync(request);
                string data = response.Body.Data;
                Console.WriteLine("OCR处理完成,开始进行本地处理...");
                string content = JsonHelper.JsonToString(data);
                return content;
            }
        }
        catch (TeaException error)
        {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            Console.WriteLine(error.Message);
            // 诊断地址
            Console.WriteLine(error.Data["Recommend"]);
            AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
        }
        catch (Exception _error)
        {
            TeaException error = new TeaException(new Dictionary<string, object>
            {
                { "message", _error.Message }
            });
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            Console.WriteLine(error.Message);
            // 诊断地址
            Console.WriteLine(error.Data["Recommend"]);
            AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
        }
        return "解析出现错误";
    }
}